
let handlingCount = 0;   // 正在处理的请求数
let global = {};        // 全局数据
import puppeteer from "puppeteer";
import fs from 'fs';
import dayjs from 'dayjs';
//import axios from "axios";
async function launchBrowser() {
    try {
        const browser = await puppeteer.launch({
            /* args: ['--no-sandbox', '--disable-setuid-sandbox', '--enable-accelerated-2d-canvas', '--enable-aggressive-domstorage-flushing'], */
            args: [
                '–disable-gpu',
                '–disable-dev-shm-usage',
                '–disable-setuid-sandbox',
                '–no-first-run',
                '–no-sandbox',
                '–no-zygote',
                '–single-process'
            ],
            ignoreHTTPSErrors: true,
            headless: true,
            timeout: 60000,

        });
        const wsAddress = browser.wsEndpoint();
        const w_data = Buffer.from(wsAddress);
        global.wsa = w_data;
        global.browser = browser;
        console.log('chrome内核启动成功')
    } catch (e) {
        console.log(e)
    }
}
launchBrowser();
async function getNewPage() {
    const browser = await puppeteer.connect({
        browserWSEndpoint: global.wsa
    });
    console.log('open Page')
    return browser.newPage();
}

export default  eventHandler(async(req, res) => {
    // 连接数 + 1
    ++handlingCount;
    console.log(`正在处理的连接数${handlingCount}`)
    // 未超过最大连接数，进行生成
    if (handlingCount <= 2) {
        const startTime = dayjs();  // 打印开始时间
        const page = await getNewPage();    // 开启一个新的标签页
        await page.goto('http://localhost:3000/pdf', { waitUntil: 'networkidle0' }) // 等待响应加载
        // 页头模板， 详情查看 http://puppeteerjs.com/#?product=Puppeteer&version=v19.2.2&show=api-pagepdfoptions
        const header = `
        <div style="width:calc(100% - 28px);margin-top: -20px; font-size:8px; padding:15px 14px;display: flex; justify-content: space-between; border-bottom:1px solid #333; font-weight: bold;">
                <div style="width: 100%; display: flex; align-items:center;">
                <span style="color: #333; font-size: 12px;"> 我是页头 </span>
                <span style="margin-left: 32px;font-size: 12px;">
                作者： <a  style=" font-size: 12px;" href="https://juejin.cn/user/4332493267283560" type="primary"> Damon </a>
             </span>
                </div>
          </div>`
      // 页尾模板， 详情查看 http://puppeteerjs.com/#?product=Puppeteer&version=v19.2.2&show=api-pagepdfoptions
      const footer = `
      <div style="width:calc(100% - 28px);margin-bottom: -20px; font-size:8px; padding:12px 14px;border-top:1px solid #333; font-weight: bold; text-align: left;">
              <div style="width: 100%; display: flex; justify-content: space-between;">
                <span style="color: #333; font-size: 12px;width: 45%;">
                  <span> 我是左页脚 </span>
                </span>
                <span style="color: #333; font-size: 12px;width: 45%;">
                <span> 我是右页脚  </span>
              </span>
              </div>
              <div style="width: 100%; text-align:center; margin-top: 8px;  font-size: 12px;">
                  第 <span style="color: #333; font-size: 12px;" class="pageNumber"></span> 页
              </div>
      </div>`
      // PDF尺寸设置
      const pdfConfig = {
        //纸张尺寸
        format: 'A4',
        //打印背景,默认为false
        //printBackground: true,
        /*  width: '1300px',
         height: '1848px', */
        //不展示页眉
        margin: {
          top: '110px',
          bottom: '150px',
          left: '20px',
          right: '30px',
        },
        /* format: {
          width: 550
        }, */
        // scale: 0.99,
        displayHeaderFooter: true,  // 是否展示页头页脚
        preferCSSPageSize: true,    // 页面优先级声明CSS
        printBackground: true,      // 是否打印背景，CSS
        footerTemplate: footer,     // 页尾模板
        headerTemplate: header     // 页眉模板 /* (await axios.get('http://localhost:3000/header')).data */
      }

      await page.addStyleTag({
        content: '@page { size: 1588px 2246px; }',  // 设置页面高度和宽度
      })
      const result = await page.pdf(pdfConfig); // 生成 PDF 
      const endTime = dayjs();  // 获取结束时间
      console.log(`生成时间： ${ endTime.diff(startTime, 'second', true) }s`);      // 生成耗时
      fs.writeFileSync(`./${dayjs().format('YYYY_MM_DD_HH_mm_ss')}.pdf`, result)    // 写入文件

        await page.close(); // 关闭标签页
        --handlingCount;
        return {
            code: 200,
            message: '返回成功',
            blob: result    
        }
    }
    // 超过最大处理任务则返回提示
    else {
        --handlingCount;
        console.log('当前人数过多，请稍后再尝试')
        return {
            code: 202,
            message: '当前人数过多，请稍后再尝试'
        }
    }
})